import { User } from "../../../modeal/user.js";
import { IsMobile } from "../../../utils/util.js"
import { GetTime } from "../../../utils/util.js"
const user = new User()
Page({


  data: {
    tabs: [{ name: "外卖配送", idx: 0 }, { name: "到店自提", idx: 1 }],
    currentIndex: 0,
    orderType: '3',
    remarkText: '口味，偏好等',
    mobile: '',
    carInfo: {},  //购物车
    selectedSite: {}, //选中的地址
    selectedSiteId: null, //选中的地址id
    canUseCoupon: [],//可用的优惠券
    selectedCoupon: {},  //选中的优惠券
    selectedCouponId: null,  //选中的优惠券id
    finalPayment: 0, //最终支付费用
    nowTime: {},   //当前时间
    zitiTime: {},
    hasZiTime: false,
    takeOutTime: {},

  },

  onLoad: function (options) {
    let shopInfo = wx.getStorageSync('shopInfo')
    let userinfo = wx.getStorageSync('userinfo')
    let myLocation = wx.getStorageSync('myLocation')
    this.setData({ shopInfo, userinfo, myLocation })
    this.getCarList();   //加载购物车数据
    this.getOrderType();   //获取订单类型
    this.getMyCoupon();    //获的我可用的优惠券
    this.getTime();      // 获取当前时间
  },

  onReady: function () { },
  onShow: function () {
    this.countFinallPay()
  },

  //获取当前时间
  getTime () {
    let nowTime = GetTime()
    this.setData({ nowTime })
  },

  // 计算最终费用
  countFinallPay () {
    let carInfo = this.data.carInfo
    let currentCouponPrice = this.data.selectedCoupon.coupon_price || 0  //优惠券
    let finalPayment = parseInt(carInfo.car_amount) - parseInt(currentCouponPrice)
    this.setData({ finalPayment })
  },

  // 加载购物车数据
  getCarList () {
    let shopId = this.data.shopInfo.id
    let orderType = this.data.orderType
    user.getCarList(shopId, orderType).then(res => {
      this.setData({ carInfo: res })
      this.countFinallPay()
    })
  },

  // 获的我可用的优惠券
  getMyCoupon () {
    user.getMyCoupon().then(res => {
      this.setData({ canUseCoupon: res })
    })
  },

  // 切换tab
  tabClick (e) {
    let currentIndex = e.currentTarget.dataset.idx
    this.setData({ currentIndex })
    this.getOrderType()  //根据tab 获取orderty状态
  },

  // swiper
  swiper (e) {
    this.setData({ currentIndex: e.detail.current })
    this.getOrderType()  //根据tab 获取orderty状态
  },

  // 根据tab状态获取orderType状态
  getOrderType () {
    let currentIndex = this.data.currentIndex
    let orderType = ""
    currentIndex ? orderType = "2" : orderType = "3"
    this.setData({ orderType })
    this.getCarList()
  },


  // 选择收货地址
  chooseSite () {
    wx.navigateTo({ url: "/pages/user/site/index/index" })
  },

  // 留言
  goRemark () {
    wx.navigateTo({ url: "/pages/shopping/common/remark/remark" })
  },

  // 自提时间
  zitiTime (e) {
    let time = e.detail.value

    let temp = this.data.nowTime

    let data = temp.year + "-" + temp.month + "-" + temp.day
    let zitiTime = { data, time }
    this.setData({ zitiTime, hasZiTime: true })

  },


  //提交订单
  submit () {
    let minToGo = this.data.shopInfo.min_togo_amount  //最小起送
    let payMoney = this.data.carInfo.car_amount + this.data.carInfo.packing
    let orderType = this.data.orderType;
    let siteId = this.data.selectedSiteId;
    let currentCouponPrice = this.data.selectedCoupon.coupon_price || 0
    let isEnoughSpec = payMoney - currentCouponPrice - minToGo    //是否够起送
    console.log(isEnoughSpec);

    if (orderType == 3) {
      // 外卖 未选择地址
      if (!siteId) {
        wx.showToast({ title: "请选择地址" })
        return;
      }
      if (isEnoughSpec < 0) {
        wx.showModal({
          content: "未达到本店" + minToGo + "元最小金额",
          showCancel: false
        })
        return;
      }
    }
    wx.showActionSheet({
      itemList: ['余额支付', '微信支付'],
      success: res => {
        let paytype = res.tapIndex + 1
        this.pay(paytype)
      },
      fail: err => { console.log(err.errMsg) }
    })
  },

  // pay 
  pay (paytype) {
    let userinfo = wx.getStorageSync('userinfo')
    let carInfo = this.data.carInfo
    let currentCouponPrice = this.data.selectedCoupon.coupon_price || 0  //优惠券

    if (paytype == 1) {
      // 余额支付 ===>判断余额是否足够
      let isEnoughMoney = userinfo.balance - carInfo.car_amount - carInfo.packing - carInfo.freight - currentCouponPrice
      if (isEnoughMoney < 0) {
        wx.showToast({ title: "余额不足" });
        return;
      }
    }

    this.placeOrde(paytype)  //下单
  },

  // 下单
  // address_id,coupon_id,date,deskid,jc_count,location, ordertype,paytype,remark,shops,time,lastpay,mobile
  placeOrde (paytype) {
    let mobile = this.data.mobile
    let myLocation = this.data.myLocation;
    let address_id = this.data.selectedSiteId;
    let coupon_id = this.data.selectedCouponId;
    let date = "";
    let deskid = '';
    let jc_count = '';
    let location = { latitude: myLocation.latitude, longitude: myLocation.latitude };
    let ordertype = this.data.orderType;
    let remark = this.data.remarkText == "口味，偏好等" ? '' : this.data.remarkText;  //备注
    let shops = this.data.shopInfo.shopname;
    let time = ''
    let lastpay = 0  //立即支付

    user.placeOrder(address_id, coupon_id, date, deskid, jc_count, location, ordertype, paytype, remark, shops, time, lastpay, mobile).then(res => {
      wx.setStorageSync('oid', res)
      paytype == 1 ? this.balancePayS() : this.wxpay(res)
    })
  },

  // 余额支付陈宫
  balancePayS () {
    wx.showToast({
      title: "支付成功",
      icon: "success"
    })
    // 清除缓存数据
    wx.removeStorageSync('oid')
    wx.removeStorageSync('deskid')
    wx.navigateTo({ url: "/pages/shopping/pays/pays" })
  },

  // 微信支付
  wxpay (oid) {
    let amount = 0
    user.wxPay(amount, oid).then(res => {
      wx.showModal({
        content: "上线对接"
      })
    })
  },

  // 微信发起支付
  payment () {
    wx.requestPayment({
      timeStamp: String(data.timeStamp),
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success: function (res) {
        // 清除缓存数据
        wx.removeStorageSync('oid')
        wx.removeStorageSync('deskid')
        wx.showModal({
          title: '订单提示',
          content: '支付成功',
          showCancel: false,
          success: res => {
            wx.redirectTo({ url: '/pages/shopping/pays/pays' });
          },
          fail: err => {
            wx.showModal({
              title: '订单提示',
              content: '订单支付取消',
              showCancel: false,
              success: function () {
                wx.redirectTo({ url: "/pages/user/myOrder/myOrder" });
              }
            });
          },
        });
      }
    })
  }





})